from django.shortcuts import redirect
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse, HttpResponseNotFound
from django.utils import simplejson
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User, get_hexdigest

from models import RegistrationProfile

def ext_login(request):
    json = {
        'errors': {},
        'text': {},
        'success': False,
    }
    user = authenticate(username=request.POST['username'],password=request.POST['password'])
    if user is not None:
        if user.is_active:
            login(request, user)
            json['success'] = True
            json['text']['welcome'] = 'Welcome, %s!' % (user.get_full_name(),)
            json['next'] = request.REQUEST.get('next', '/GH')
        else:
            # Return a 'disabled account' error message
            json['errors']['username'] = 'Account disabled.'
    else:
        # Return an 'invalid login' error message.
            json['errors']['username'] = 'Username and/or password invalid.'
    return HttpResponse(simplejson.dumps(json, cls=DjangoJSONEncoder))


def validate_username(request):
    if request.method == "POST":
        try:
            User.objects.get(username = request.POST['reg_username'])
        except User.DoesNotExist:
            resp = dict(success=True)
            return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder)) 
        except:
            import traceback
            print repr(traceback.print_exc())
            resp = dict(success=False, errors="Server Error")
            return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder))
        else:
            resp = dict(success=False, errors="This username has been taken")
            return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder))
    else:
        return HttpResponseNotFound('<h1>Can not go to this view unless with method other than  POST </h1>') 
    

def simple_registration(request):
    if request.method == "POST":
        try:
            User.objects.get(username = request.POST['reg_username'])
        except User.DoesNotExist:
            resp = dict(success=True)
            import random
            salt = get_hexdigest('sha1', str(random.random()), str(random.random()))[:5]
            hsh = get_hexdigest('sha1', salt, request.POST['reg_password'])
            gen_password = '%s$%s$%s' % ('sha1', salt, hsh)
            new_user = User(username = request.POST['reg_username'], password = gen_password, \
                               first_name = request.POST.get('firstName'), last_name = request.POST.get('lastName'), 
                               email = request.POST['email'])
            new_user.save()
            new_profile = RegistrationProfile(user = new_user, zipcode = request.POST.get('zipcode'))
            new_profile.save()
            return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder))
        except:
            import traceback
            print repr(traceback.print_exc())
            resp = dict(success=False, errors="Server Error")
            return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder))
        else:
            resp = dict(success=False, errors="This username has been taken")
            return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder))
    else:
        return HttpResponseNotFound('<h1>Can not go to this view unless with method other than  POST </h1>')
    


def logout_view(request):
    logout(request)
    # Redirect to a success page.
    return redirect('auth_login') 